from contextvars import ContextVar, Token

from src.models import FamilyMember

_user = ContextVar("_user")


async def set_user_context(member_id: int) -> Token:
    """设置用户上下文"""
    from src.crud.family_crud import get_family_member_by_id
    from src.database import AsyncSessionLocal

    async with AsyncSessionLocal() as db:
        member = await get_family_member_by_id(db=db, member_id=member_id)
        return _user.set(member)


def clean_user_context(token: Token):
    """清理用户context"""
    _user.reset(token)


def get_user() -> FamilyMember | None:
    """获取当前用户信息"""
    try:
        return _user.get()
    except LookupError:
        return None
